﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using NewLife.Data;
using NewLife.Log;
using NewLife.Model;
using NewLife.Net;

using NewLife.Net.Modbus1;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static StackExchange.Redis.Role;

namespace WinFormsApp1;

public partial class Form3 : Form, ILog
{
    private TcpServer _server;
    private ModbusSlave _slave1;
    private ModbusSlave _slave2;
    private ModbusSlave _slave3;
    private ModbusMaster _master;

    public bool Enable { get; set; }
    public LogLevel Level { get; set; }

    public Form3()
    {
        InitializeComponent();
    }

    private void InitializeModbusServer()
    {
        try
        {
            _master = new ModbusMaster();
            _master.Delay = 100;
            _master.Log = this;
            _server = new TcpServer
            {
                Port = 502
            };
            _server.Start();
            var sessionServer = new TcpSession(_server.Client);

          
            _server.NewSession += (s, e) =>
            {
                var session = e.Session as TcpSession;
                _master.Transport = session;
                session.Received += (s1, e1) =>
                {
                    //  var response = _slave.Process(e1.Packet);
                    //session.Send(response);
                    //this.CreateControl();
                    //Invoke(new Action(() =>
                    //{
                    //    txtLog.AppendText($"收到请求: {e1.Packet.ToHex()}\n");
                    //}));
                };
            };

            _slave1 = new ModbusSlave
            {
                Host = 1
            };
            _slave2 = new ModbusSlave
            {
                Host = 1
            };
            _slave3 = new ModbusSlave
            {
                Host = 1
            };
            var session = new TcpSession();
            session.Remote = new NetUri(NetType.Tcp, "127.0.0.1", 502);
            _slave1.Listen(session);
            // session.Send(new Packet(new byte[] { 0x01, 02 }));
            session.Received += (s1, e1) =>
            {
                var se = s1 as TcpSession;
                //Invoke(new Action(() =>
                //{
                //    txtLog.AppendText($"收到请求: {e1.Packet.ToHex()}\n");
                //}));

                //  这里我想答复主机指令改如何写代码

                session.Send(e1.Packet);
            };
            // var re = _master.ReadCoil(1);
            //var session1 = new TcpSession();
            //session1.Remote = new NetUri(NetType.Tcp, "127.0.0.1", 502);
            //_slave2.Listen(session1);

            txtLog.AppendText("Modbus TCP 服务器已启动。\n");
        }
        catch (Exception ex)
        {
        }
    }

    private void Form3_FormClosing(object sender, FormClosingEventArgs e)
    {
        _server.Stop("guanbi ");
    }

    private void Form3_Load(object sender, EventArgs e)
    {
        InitializeModbusServer();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            var re = _master.ReadCoil(1);
        }
        catch (Exception ex)
        {
        }
    }

    public void Write(LogLevel level, string format, params object?[] args)
    {
    }

    public void Debug(string format, params object?[] args)
    {
    }

    public void Info(string format, params object?[] args)
    {
        Invoke(new Action(() =>
        {
            var log = string.Format(format, args);
            txtLog.AppendText($"收到请求: {format}\n");
        }));
    }

    public void Warn(string format, params object?[] args)
    {
    }

    public void Error(string format, params object?[] args)
    {
    }

    public void Fatal(string format, params object?[] args)
    {
    }
}